import { asyncRouterMap, constantRouterMap } from '../../router/index'

/**
 * 生成路由表
 */

// 判断路由的 meta.roles 是否存在当前权限的数据里
function hasPermission (roles, router) {
  if (router.meta && router.meta.roles) {
    return roles.some(role => router.meta.roles.indexOf(role) > -1)
  } else {
    return true
  }
}

/**
 * 递归过滤 异步路由表 / asyncRouterMap，返回符合用户角色权限的路由表
 * 1. 通过 filter 递归得到 router 元素 ；
 * 2. 然后根据 roles（权限数据）进行过滤
 * 3. 判断如果 router 元素的 children 属性也还有值，那就把 router.children 再走一边 1
 */
function filterAsyncRouter (asyncRouterMap, roles) {
  const filterRouters = asyncRouterMap.filter(router => {
    if (hasPermission(roles, router)) {
      if (router.children && router.children.length) {
        router.children = filterAsyncRouter(router.children, roles)
      }
      return true
    }
    return false
  })

  return filterRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    // 过滤路由表
    GenerateRoutes ({ commit }, data) {
      return new Promise((resolve) => {
        const { roles } = data
        const filterRouters = filterAsyncRouter(asyncRouterMap, roles)
        commit('SET_ROUTERS', filterRouters)
        resolve()
      })
    }
  }
}

export default permission
